// MainActivity.java
package com.poker.monitor;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.poker.monitor.ocr.OcrService;
import com.poker.monitor.recognition.RegionRecognizer;
import com.poker.monitor.service.ScreenCaptureService;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_MEDIA_PROJECTION = 1;
    private Button startCaptureButton;
    private RecyclerView playersRecyclerView;
    private boolean isMonitoring = false;
    private MediaProjectionManager mediaProjectionManager;
    private ActivityResultLauncher<Intent> mediaProjectionLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        setupMediaProjectionLauncher();
        initViews();
        setupListeners();
    }

    private void initViews() {
        startCaptureButton = findViewById(R.id.startCaptureButton);
        playersRecyclerView = findViewById(R.id.playersRecyclerView);
        playersRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    private void setupListeners() {
        startCaptureButton.setOnClickListener(v -> toggleMonitoring());
    }

    private void setupMediaProjectionLauncher() {
        mediaProjectionLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        ScreenCaptureService.resultCode = result.getResultCode();
                        ScreenCaptureService.resultData = result.getData();
                        startScreenCaptureService();
                    } else {
                        isMonitoring = false;
                        startCaptureButton.setText("开始监控");
                        Toast.makeText(this, "未获取屏幕录制权限", Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }

    private void toggleMonitoring() {
        isMonitoring = !isMonitoring;
        if (isMonitoring) {
            startCaptureButton.setText("停止监控");
            requestScreenCapturePermission();
        } else {
            startCaptureButton.setText("开始监控");
            stopMonitoring();
        }
    }

    private void requestScreenCapturePermission() {
        Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
        mediaProjectionLauncher.launch(captureIntent);
    }

    private void startScreenCaptureService() {
        Intent serviceIntent = new Intent(this, ScreenCaptureService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(serviceIntent);
        } else {
            startService(serviceIntent);
        }
        bindService(new Intent(this, ScreenCaptureService.class), serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ScreenCaptureService.LocalBinder binder = (ScreenCaptureService.LocalBinder) service;
            ScreenCaptureService screenCaptureService = binder.getService();

            // 初始化OCR服务和区域识别器
            OcrService ocrService = new OcrService();
            RegionRecognizer regionRecognizer = new RegionRecognizer();
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            regionRecognizer.updateRegions(metrics.widthPixels, metrics.heightPixels);

            Toast.makeText(MainActivity.this, "开始监控", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    private void stopMonitoring() {
        unbindService(serviceConnection);
        Intent intent = new Intent(this, ScreenCaptureService.class);
        stopService(intent);
        Toast.makeText(this, "停止监控", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMonitoring();
    }
}
